package com.nageoffer.jobtrain.projects.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.jobtrain.projects.common.biz.user.UserContext;
import com.nageoffer.jobtrain.projects.dao.entity.MessageDO;
import com.nageoffer.jobtrain.projects.dao.mapper.MessageMapper;
import com.nageoffer.jobtrain.projects.dto.req.MessagePageListReqDTO;
import com.nageoffer.jobtrain.projects.dto.resp.MessagePageListRespDTO;
import com.nageoffer.jobtrain.projects.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 系统消息记录接口实现层
 * author：唐晨
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, MessageDO> implements MessageService {
    private final MessageMapper messageMapper;

    @Override
    public IPage<MessagePageListRespDTO> messagePageList(MessagePageListReqDTO requestParam) {
        Page<MessageDO> page = new Page<>(requestParam.getCurrent(), requestParam.getSize());
        LambdaQueryWrapper<MessageDO> queryWrapper = Wrappers.lambdaQuery(MessageDO.class)
                .eq(MessageDO::getReceive, UserContext.getUsername())
                .eq(MessageDO::getDelFlag, 0)
                .orderByDesc(MessageDO::getCreateTime);
        Page<MessageDO> pageMessageList = baseMapper.selectPage(page, queryWrapper);
        // 转换分页数据
        Page<MessagePageListRespDTO> resultPage = new Page<>();
        resultPage.setCurrent(pageMessageList.getCurrent());
        resultPage.setSize(pageMessageList.getSize());
        resultPage.setTotal(pageMessageList.getTotal());
        resultPage.setPages(pageMessageList.getPages());
        List<MessagePageListRespDTO> dtoList = pageMessageList.getRecords().stream()
                .map(this::handlerConvertToRespDTO)
                .toList();
        resultPage.setRecords(dtoList);
        return resultPage;
    }

    // 返回值类型转化函数
    private MessagePageListRespDTO handlerConvertToRespDTO(MessageDO message) {
        return MessagePageListRespDTO.builder()
                .id(message.getId())
                .title(message.getTitle())
                .content(message.getContent())
                .build();
    }

    @Override
    public void deleteMessage(Long messageId) {
        LambdaUpdateWrapper<MessageDO> updateWrapper = Wrappers.lambdaUpdate(MessageDO.class)
                .eq(MessageDO::getReceive, UserContext.getUsername())
                .eq(MessageDO::getId, messageId)
                .set(MessageDO::getDelFlag, 1);
        messageMapper.update(updateWrapper);
    }
}
